<template>
  <div class="ele-body">
    <!-- 搜索表单 -->
    <div class="block-interval">
      <a-card :bordered="false">
        <a-form layout="inline" :model="where">
          <a-row>

            <a-form-item label="设备ID:">
              <a-input v-model:value.trim="where.recordId" placeholder="请输入设备ID" allow-clear />
            </a-form-item>

            <a-form-item label="MACID:">
              <a-input v-model:value.trim="where.macId" placeholder="请输入设备编码" allow-clear />
            </a-form-item>
            
            <a-form-item label="版本:">
              <a-input v-model:value.trim="where.version" placeholder="请输入设备版本" allow-clear />
            </a-form-item>
            <a-form-item label="相机型号:">
              <a-input v-model:value.trim="where.softModel" placeholder="请输入相机型号" allow-clear />
            </a-form-item>

            <a-form-item label="厂商:">
              <a-select
                show-search
                v-model:value="where.factory"
                style="width: 120px"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                allow-clear
              >
                <a-select-option value='guangzhou'>广州那家</a-select-option>
                <a-select-option value='DHUA'>大华</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="状态:">
              <a-select
                show-search
                v-model:value="where.queryRecordStatus"
                style="width: 120px"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                allow-clear
              >
                <a-select-option value='1'>在线</a-select-option>
                <a-select-option value='2'>离线</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="所属牧场:" name="orgId">
              <a-select
                show-search
                v-model:value="where.queryRanchId"
                placeholder="请选择所属牧场"
                style="width: 205px;"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                @change="selectRanch"
                allow-clear
                @clear="clearRanchRelated"
              >
                <a-select-option v-for="item in ranchList" :key="item.ranchId" >
                  {{ item.ranchName }}
                </a-select-option>
              </a-select>
            </a-form-item>


            <a-form-item label="所属牛舍:" name="oxtId">
              <a-select
                show-search
                v-model:value="where.queryOxtallId"
                placeholder="请选择所属牛舍"
                style="width: 200px"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                @change="selectOxtall"
                allow-clear
                @clear="clearOxtallRelated"
              >
                <a-select-option v-for="item in oxtallList" :key="item.oxtallId" >
                  {{ item.oxtallName }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="所属区域:" name="areaId">
              <a-select
                show-search
                v-model:value="where.queryAreaId"
                placeholder="请选择所属区域"
                style="width: 200px"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                allow-clear
              >
                <a-select-option v-for="item in areaList" :key="item.areaId" >
                  {{ item.areaName }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="设备标签:">
              <a-input v-model:value.trim="where.lable1" placeholder="请输入设备标签" allow-clear />
            </a-form-item>

            <a-form-item class="ele-text-center">
              <a-space>
                <a-button type="primary" @click="reload">查询</a-button>
                <a-button @click="reset">重置</a-button>
              </a-space>
            </a-form-item>

          </a-row>
        </a-form>
      </a-card>
    </div>
    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="groupId"
          :datasource="datasource"
          :columns="columns"
          :where="where"
          :scroll="{ x: 'max-content' }"
        >

          <!-- table上边工具栏 -->
          <template #toolbar>
            <a-space>
              <a-button type="primary" @click="openEdit()">
                <template #icon>
                  <plus-outlined />
                </template>
                <span>新建</span>
              </a-button>
            </a-space>
          </template>

      
          <!-- table操作栏按钮 -->
          <template #bodyCell="{ column, record }">

            <!-- 牧场字段可编辑 -->
            <template v-if="column.dataIndex === 'ranchName'">
              <div v-if="editingId === record.recordId && editingField === 'ranchName'">
                <div v-permission="['PROPERTY_MGR_DEVICEMGR_AICAMERA_CAMERALIST_OXTRANCH_EDIT_BUTTON']" style="display: flex; flex-direction: column; position: relative;">
                  <a-select
                    v-model:value="editingRanchId"
                    style="width: 180px; margin-bottom: 4px;"
                    placeholder="请选择牧场"
                    :dropdown-style="{ maxWidth: '300px' }"
                    :dropdown-match-select-width="false"
                    placement="bottomLeft"
                  >
                    <a-select-option v-for="item in tempRanchList" :key="item.ranchId">
                      {{ item.ranchName }}
                    </a-select-option>
                  </a-select>
                  <div style="display: flex; justify-content: center;">
                    <a-button type="link" size="small" @click="saveRanch(record)" style="padding: 0 8px;">
                      <check-outlined />
                    </a-button>
                    <a-button type="link" size="small" @click="cancelEdit" style="padding: 0 8px;">
                      <close-outlined />
                    </a-button>
                  </div>
                </div>
              </div>
              <div v-else>
                <a-space>
                  <span>{{ record.ranchName }}</span>
                  <a-button v-permission="['PROPERTY_MGR_DEVICEMGR_AICAMERA_CAMERALIST_OXTRANCH_EDIT_BUTTON']" type="link" size="small" @click="startEditRanch(record)">
                    <edit-outlined />
                  </a-button>
                </a-space>
              </div>
            </template>
            
            <!-- 牛舍字段可编辑 -->
            <template v-if="column.dataIndex === 'oxtallName'">
              <div v-if="editingId === record.recordId && editingField === 'oxtallName'">
                <div v-permission="['PROPERTY_MGR_DEVICEMGR_AICAMERA_CAMERALIST_OXTRANCH_EDIT_BUTTON']" style="display: flex; flex-direction: column;">
                  <a-select
                    v-model:value="editingOxtallId"
                    style="width: 120px; margin-bottom: 4px;"
                    placeholder="请选择牛舍"
                  >
                    <a-select-option v-for="item in tempOxtallList" :key="item.oxtallId">
                      {{ item.oxtallName }}
                    </a-select-option>
                  </a-select>
                  <div style="display: flex; justify-content: center;">
                    <a-button type="link" size="small" @click="saveOxtall(record)" style="padding: 0 8px;">
                      <check-outlined />
                    </a-button>
                    <a-button type="link" size="small" @click="cancelEdit" style="padding: 0 8px;">
                      <close-outlined />
                    </a-button>
                  </div>
                </div>
              </div>
              <div v-else>
                <a-space>
                  <span>{{ record.oxtallName }}</span>
                  <a-button v-permission="['PROPERTY_MGR_DEVICEMGR_AICAMERA_CAMERALIST_OXTRANCH_EDIT_BUTTON']" type="link" size="small" @click="startEditOxtall(record)">
                    <edit-outlined />
                  </a-button>
                </a-space>
              </div>
            </template>
            
            <!-- 区域字段可编辑 -->
            <template v-if="column.dataIndex === 'areaName'">
              <div v-if="editingId === record.recordId && editingField === 'areaName'">
                <div v-permission="['PROPERTY_MGR_DEVICEMGR_AICAMERA_CAMERALIST_OXTRANCH_EDIT_BUTTON']" style="display: flex; flex-direction: column;">
                  <a-select
                    v-model:value="editingAreaId"
                    style="width: 120px; margin-bottom: 4px;"
                    placeholder="请选择区域"
                  >
                    <a-select-option v-for="item in tempAreaList" :key="item.areaId">
                      {{ item.areaName }}
                    </a-select-option>
                  </a-select>
                  <div style="display: flex; justify-content: center;">
                    <a-button type="link" size="small" @click="saveArea(record)" style="padding: 0 8px;">
                      <check-outlined />
                    </a-button>
                    <a-button type="link" size="small" @click="cancelEdit" style="padding: 0 8px;">
                      <close-outlined />
                    </a-button>
                  </div>
                </div>
              </div>
              <div v-else>
                <a-space>
                  <span>{{ record.areaName }}</span>
                  <a-button v-permission="['PROPERTY_MGR_DEVICEMGR_AICAMERA_CAMERALIST_OXTRANCH_EDIT_BUTTON']" type="link" size="small" @click="startEditArea(record)">
                    <edit-outlined />
                  </a-button>
                </a-space>
              </div>
            </template>

            <!-- 牛栏字段可编辑 -->
            <template v-if="column.dataIndex === 'fenceName'">
              <div v-if="editingId === record.recordId && editingField === 'fenceName'">
                <div v-permission="['PROPERTY_MGR_DEVICEMGR_AICAMERA_CAMERALIST_OXTRANCH_EDIT_BUTTON']" style="display: flex; flex-direction: column;">
                  <a-select
                    v-model:value="editingFenceId"
                    style="width: 120px; margin-bottom: 4px;"
                    placeholder="请选择牛栏"
                  >
                    <a-select-option v-for="item in tempFenceList" :key="item.fenceId">
                      {{ item.fenceName }}
                    </a-select-option>
                  </a-select>
                  <div style="display: flex; justify-content: center;">
                    <a-button type="link" size="small" @click="saveFence(record)" style="padding: 0 8px;">
                      <check-outlined />
                    </a-button>
                    <a-button type="link" size="small" @click="cancelEdit" style="padding: 0 8px;">
                      <close-outlined />
                    </a-button>
                  </div>
                </div>
              </div>
              <div v-else>
                <a-space>
                  <span>{{ record.fenceName }}</span>
                  <a-button v-permission="['PROPERTY_MGR_DEVICEMGR_AICAMERA_CAMERALIST_OXTRANCH_EDIT_BUTTON']" type="link" size="small" @click="startEditFence(record)">
                    <edit-outlined />
                  </a-button>
                </a-space>
              </div>
            </template>

            <!-- 标签字段可编辑 -->
            <template v-if="column.dataIndex === 'lable1'">
              <div v-if="editingId === record.recordId && editingField === 'lable1'">
                <div v-permission="['PROPERTY_MGR_DEVICEMGR_AICAMERA_CAMERALIST_OXTRANCH_EDIT_BUTTON']" style="display: flex; flex-direction: column;">
                  <a-input
                    v-model:value="editingValue"
                    style="width: 120px; margin-bottom: 4px;"
                    placeholder="请输入标签"
                  />
                  <div style="display: flex; justify-content: center;">
                    <a-button type="link" size="small" @click="saveLabel(record)" style="padding: 0 8px;">
                      <check-outlined />
                    </a-button>
                    <a-button type="link" size="small" @click="cancelEdit" style="padding: 0 8px;">
                      <close-outlined />
                    </a-button>
                  </div>
                </div>
              </div>
              <div v-else>
                <a-space>
                  <span>{{ record.lable1 }}</span>
                  <a-button v-permission="['PROPERTY_MGR_DEVICEMGR_AICAMERA_CAMERALIST_OXTRANCH_EDIT_BUTTON']" type="link" size="small" @click="startEditLabel(record)">
                    <edit-outlined />
                  </a-button>
                </a-space>
              </div>
            </template>

            <!-- 其他列的模板 -->
            <template v-if="column.key === 'statuscolumn'">
              <a-tag v-if="record.recordStatus == 1" color="green">在线</a-tag>
              <a-tag v-else color="red">离线</a-tag>
            </template>

            <!-- 其他列的模板 -->
            <template v-if="column.key === 'biaozhuCountColumn'">
              <div>
                <div>
                  <a-tag color="#87d068">已标注: {{ record.biaozhuCount }}</a-tag>
                </div>
                <div style="margin-top: 2px;">
                  <a-tag color="#f50" v-if="record.wifiRelayCount - record.biaozhuCount > 0">
                    待标注: {{ record.wifiRelayCount - record.biaozhuCount }}
                  </a-tag>
                  <a-tag color="#87d068" v-else>全部已标注</a-tag>
                </div>
              </div>
            </template>
            <template v-if="column.key === 'versionColumn'">
              <div>
                <div>型号：{{ record.softModel || '-' }}</div>
                <div style="margin-top: 2px;">版本：{{ record.version || '-' }}</div>
              </div>
            </template>
            <!-- table操作栏按钮 -->
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openManager(record)">管理</a>
                <a-divider type="vertical" />
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>
     <!-- 编辑弹窗 -->
     <DeviceSpraycameraModal v-if="showCameraModal" v-model:visible="showCameraModal" :data="current" @done="reload"  />
  </div>
</template>

<script>
import { PlusOutlined } from '@ant-design/icons-vue';
import { DeviceRecordApi } from '@/api/property/DeviceRecordApi';
import {FenceApi} from '@/api/property/FenceApi';
import {DeviceSprayCameraGroupApi} from "@/api/property/spraycamera/DeviceSprayCameraGroupApi";
import { RanchApi } from '@/api/property/RanchApi';
import { OxtallApi } from '@/api/property/OxtallApi';
import { AreaApi } from '@/api/property/AreaApi';
import { message } from 'ant-design-vue';
import { DeviceSprayCameraApi } from '@/api/property/spraycamera/DeviceSprayCameraApi';
import DeviceSpraycameraModal from '@/views/property/device/spraycamera/spraycamera-modal.vue'
import { EditOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons-vue';
export default {
  name: 'DeviceManagerdeviceCameraList',
  components: {
    PlusOutlined,
    DeviceSpraycameraModal,
    EditOutlined,
    CheckOutlined,
    CloseOutlined,
  },
  async mounted() {
  },
  async created() {
    let that = this;
    RanchApi.list({}).then(resp => {
      let _ranchList = (resp ? resp.data : null) || [];
      this.ranchList = _ranchList;
      if (_ranchList.length > 0) {
        OxtallApi.list({"orgId" : _ranchList[0].ranchId}).then(result => {
          this.oxtallList = (result ? result.data : null) || [];
          if (this.oxtallList.length > 0) {
            AreaApi.list({"oxtId" : this.oxtallList[0].oxtallId}).then(result => {
              that.areaList = (result? result.data : null) || [];
            }).catch((err) => {
              console.log(err)
            });
          }
        }).catch((err) => {
          console.log(err)
        });
      }
    });
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
          title: '设备ID',
          dataIndex: 'recordId',
          width: 90
        },
        {
          title: '标签',
          dataIndex: 'lable1',
          width: 90
        },
        {
          title: '设备状态',
          key : 'statuscolumn',
          dataIndex: 'recordStatus',
          width: 70,
        },
        {
          title: '相机',
          dataIndex: 'macId',
          width: 150
        },
        {
          title: 'IP地址',
          dataIndex: 'ip',
          width: 115
        },
        {
          title: '厂商',
          dataIndex: 'factory',
          width: 50,
          customRender: function(row) {
            if (row.text == 'DHUA') {
              return '大华';
            }  else {
              return '广州';
            }
          }
        },
        {
          title: '牧场',
          dataIndex: 'ranchName',
          width: 100
        },
        {
          title: '牛舍',
          dataIndex: 'oxtallName',
          width: 100
        },
        {
          title: '区域',
          dataIndex: 'areaName',
          width: 100
        },
        {
          title: '牛栏',
          dataIndex: 'fenceName',
          width: 100
        },
        {
          title: '喷淋板状态',
          dataIndex: 'boardlink',
          width: 100,
          customRender: function(row) {
            if (row.record.factory == 'DHUA') {
              if (row.text == 1) {
                return '正常';
              }  else {
                return '异常';
              }
            } else {
              return "-";
            }
          }
        },
        {
          title: '标注',
          key : 'biaozhuCountColumn',
          dataIndex: 'biaozhuCount',
        },
        {
          title: '型号/版本',
          key: 'versionColumn',
          dataIndex: 'version',
          width: 240,
        },
        {
          title: '操作',
          key: 'action',
          width: 80,
          align: 'center',
          fixed: 'right',
        }
      ],
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      ranchList : [],
      oxtallList : [],
      areaList : [],
      showCameraModal : false,
      editingId: null,
      editingValue: null,
      // 添加新的编辑状态变量
      editingField: null,
      editingRanchId: null,
      editingOxtallId: null,
      editingAreaId: null,
      // 临时存储编辑时的选项列表
      tempRanchList: [],
      tempOxtallList: [],
      tempAreaList: [],
      editingFenceId: null,
      tempFenceList: [],
    };
  },
  methods: {
    /**
     * 搜索按钮
     *
     * @author cancan
     * @date 2025/03/08 10:06
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({ page: 1 });
    },

    reloadCurrent(){
      const page = this.$refs.table.tablePagination.current || 1;
      this.$refs.table.reload({ page: page });
    },

    /**
     * 重置搜索
     *
     * @author cancan
     * @date 2025/03/08 10:06
     */
    reset() {
      this.where.recordId = '';
      this.where.macId = '';
      this.where.queryRecordStatus = undefined;
      this.where.queryOxtallId = undefined;
      this.where.queryRanchId = undefined;
      this.where.queryAreaId = undefined;
      this.where.softModel = '';
      this.where.version = '';
      this.where.factory = '';
      this.where.lable1 = '';
      this.$nextTick(() => {
        this.reload();
      });
    },

    /**
     * 删除
     *
     * @author cancan
     * @date 2025/03/08 10:06
     */
    async remove(row) {
      const result = await DeviceSprayCameraGroupApi.delete({ groupId: row.groupId });
      message.success(result.message);
      this.reload();
    },

    /**
     * 打开新增或编辑弹窗
     *
     * @author cancan
     * @date 2025/03/08 10:06
     */
    openManager(row) {
      this.current = row;
      this.showCameraModal = true;
    },
    /**
     * 获取表格数据
     *
     * @author fengshuonan
     * @date 2022/5/8 15:18
     */
    datasource({ page, limit, where, orders }) {
      return DeviceSprayCameraApi.findStandAlonePage({ ...where, ...orders, pageNo: page, pageSize: limit });
    },
    selectRanch(ranchId) {
      this.oxtallList = [];
      this.areaList = [];
      this.where.queryAreaId = undefined;
      this.where.queryOxtallId = undefined;
      let that = this;
      OxtallApi.list({"orgId" : ranchId}).then(result => {
        this.oxtallList = (result ? result.data : null) || [];
        if (this.oxtallList.length > 0) {
          AreaApi.list({"oxtId" : this.oxtallList[0].oxtallId}).then(result => {
            that.areaList = (result? result.data : null) || [];
          }).catch((err) => {
            console.log(err)
          });
        }
      }).catch((err) => {
        console.log(err)
      });
    },

    selectOxtall(oxtId) {
      this.areaList = [];
      this.where.queryAreaId = undefined;
      let that = this;
      AreaApi.list({"oxtId" : oxtId}).then(result => {
        that.areaList = (result? result.data : null) || [];
      }).catch((err) => {
        console.log(err)
      });
    },
    clearRanchRelated() {
      // 清空牛舍选择
      this.where.queryOxtallId = undefined;
      // 清空区域选择
      this.where.queryAreaId = undefined;
      // 清空相关列表数据
      this.oxtallList = [];
      this.areaList = [];
    },
    clearOxtallRelated() {
      // 清空区域选择
      this.where.queryAreaId = undefined;
      this.areaList = [];
    },


    /**
     * 取消编辑
     */
     cancelEdit() {
      this.editingId = null;
      this.editingValue = null;
      this.editingField = null;
      this.editingRanchId = null;
      this.editingOxtallId = null;
      this.editingAreaId = null;
      this.editingFenceId = null;
    },

    /**
     * 开始编辑牧场
     */
     async startEditRanch(record) {
      this.editingId = record.recordId;
      this.editingField = 'ranchName';
      this.editingRanchId = record.ranchId == 0 ? undefined : record.ranchId;
      
      // 获取牧场列表
      try {
        const resp = await RanchApi.list({});
        this.tempRanchList = (resp ? resp.data : null) || [];
      } catch (err) {
        console.log(err);
        message.error('获取牧场列表失败' + (err.message || '未知错误'));
      }
    },

    /**
     * 保存牧场
     */
    async saveRanch(record) {
      try {
        const updateData = {
          recordId: record.recordId,
          orgId: this.editingRanchId,
          // 清空牛舍和区域信息
          oxtId: 0,
          areaId: 0,
          fenceId: 0,
        };
        
        await DeviceRecordApi.editCsort(updateData);
        message.success('牧场更新成功');
        
        // 更新当前记录的牧场信息
        const selectedRanch = this.tempRanchList.find(item => item.ranchId === this.editingRanchId);
        if (selectedRanch) {
          record.ranchId = selectedRanch.ranchId;
          record.ranchName = selectedRanch.ranchName;
          // 清空牛舍和区域信息，因为牧场变了
          record.oxtallId = null;
          record.oxtallName = '';
          record.areaId = null;
          record.areaName = '';
          record.fenceId = null;
          record.fenceName = '';
        }
        
        this.cancelEdit();
      } catch (error) {
        message.error('牧场更新失败' + (error.message || '未知错误'));
      }
    },

    /**
     * 开始编辑牛舍
     */
    async startEditOxtall(record) {
      if (!record.ranchId) {
        message.warning('请先设置牧场');
        return;
      }
      
      this.editingId = record.recordId;
      this.editingField = 'oxtallName';
      this.editingOxtallId = record.oxtallId == '0'? undefined : record.oxtallId;
      
      // 获取牛舍列表，基于当前记录的牧场ID
      try {
        const result = await OxtallApi.list({"orgId": record.ranchId});
        this.tempOxtallList = (result ? result.data : null) || [];
        if (this.tempOxtallList.length === 0) {
          message.warning('当前牧场下没有牛舍');
        }
      } catch (err) {
        console.log(err);
        message.error('获取牛舍列表失败' + (err.message || '未知错误'));
      }
    },

    /**
     * 保存牛舍
     */
    async saveOxtall(record) {
      try {
        const updateData = {
          recordId: record.recordId,
          oxtId: this.editingOxtallId,
          // 清空区域和牛栏信息
          areaId: 0,
          fenceId: 0
        };
        
        await DeviceRecordApi.editCsort(updateData);
        message.success('牛舍更新成功');
        
        // 更新当前记录的牛舍信息
        const selectedOxtall = this.tempOxtallList.find(item => item.oxtallId === this.editingOxtallId);
        if (selectedOxtall) {
          record.oxtallId = selectedOxtall.oxtallId;
          record.oxtallName = selectedOxtall.oxtallName;
          // 清空区域和牛栏信息，因为牛舍变了
          record.areaId = null;
          record.areaName = '';
          record.fenceId = null;
          record.fenceName = '';
        }
        
        this.cancelEdit();
      } catch (error) {
        message.error('牛舍更新失败' + (error.message || '未知错误'));
      }
    },

    /**
     * 开始编辑区域
     */
    async startEditArea(record) {
      if (!record.oxtallId) {
        message.warning('请先设置牛舍');
        return;
      }
      
      this.editingId = record.recordId;
      this.editingField = 'areaName';
      this.editingAreaId = record.areaId == '0'? undefined : record.areaId;
      
      // 获取区域列表，基于当前记录的牛舍ID
      try {
        const result = await AreaApi.list({"oxtId": record.oxtallId});
        this.tempAreaList = (result ? result.data : null) || [];
        if (this.tempAreaList.length === 0) {
          message.warning('当前牛舍下没有区域');
        }
      } catch (err) {
        console.log(err);
        message.error('获取区域列表失败' + (err.message || '未知错误'));
      }
    },

    /**
     * 保存区域
     */
    async saveArea(record) {
      try {
        const updateData = {
          recordId: record.recordId,
          areaId: this.editingAreaId
        };
        
        await DeviceRecordApi.editCsort(updateData);
        message.success('区域更新成功');
        
        // 更新当前记录的区域信息
        const selectedArea = this.tempAreaList.find(item => item.areaId === this.editingAreaId);
        if (selectedArea) {
          record.areaId = selectedArea.areaId;
          record.areaName = selectedArea.areaName;
        }
        
        this.cancelEdit();
      } catch (error) {
        message.error('区域更新失败' + (error.message || '未知错误'));
      }
    },

    /**
     * 开始编辑牛栏
     */
     async startEditFence(record) {
      if (!record.oxtallId) {
        message.warning('请先设置牛舍');
        return;
      }
      
      this.editingId = record.recordId;
      this.editingField = 'fenceName';
      this.editingFenceId = record.fenceId == '0'? undefined : record.fenceId;
      
      // 获取牛栏列表，基于当前记录的牛舍ID
      try {
        // 假设有一个 FenceApi.list 方法用于获取牛栏列表
        const result = await FenceApi.list({"oxtId": record.oxtallId});
        this.tempFenceList = (result ? result.data : null) || [];
        if (this.tempFenceList.length === 0) {
          message.warning('当前牛舍下没有牛栏');
        }
      } catch (err) {
        console.log(err);
        message.error('获取牛栏列表失败' + (err.message || '未知错误'));
      }
    },

    /**
     * 保存牛栏
     */
    async saveFence(record) {
      try {
        const updateData = {
          recordId: record.recordId,
          fenceId: this.editingFenceId
        };
        let that = this;
        DeviceRecordApi.editCsort(updateData).then(() => {
          message.success('牛栏更新成功');
            // 更新当前记录的牛栏信息
          const selectedFence = that.tempFenceList.find(item => item.fenceId === that.editingFenceId);
          if (selectedFence) {
            record.fenceId = selectedFence.fenceId;
            record.fenceName = selectedFence.fenceName;
          }
          
          that.cancelEdit();
        }).catch((error) => {
          console.error('牛栏更新失败:', error);
          message.error('牛栏更新失败: ' + (error.message || '未知错误'));
        });  
      } catch (err) {
        message.error('牛栏更新失败' + (err.message || '未知错误'));
      }
    },

    // 开始编辑标签
    startEditLabel(record) {
      this.editingId = record.recordId;
      this.editingField = 'lable1';
      this.editingValue = record.lable1;
    },

    // 保存标签
    async saveLabel(record) {
      try {
        const updateData = {
          recordId: record.recordId,
          lable1: this.editingValue
        };
        
        await DeviceRecordApi.editCsort(updateData);
        message.success('修改成功');
        this.cancelEdit();
        this.reloadCurrent();
      } catch (error) {
        message.error('修改失败');
      }
    },

  }
};
</script>
